<template>
    <div class="chat-room is-always-shadow" :class="{'chat-room-single':users.length>1}"
         v-if="chatDialogVisible">
        <div class="user-left-list" v-if="users.length>1">
            <div class="chat-user" :ref="`chat-user-${item.id}`"
                 v-for="(item,index) in users" :key="index" @click="handleChooseUser(item)">
                <el-image class="user-header" :src="fileDownloadUrl+item.header"></el-image>
                <div class="user-name">
                    {{item.name}}
                </div>
                <i class="el-icon-circle-close" @click.stop="handleRemoveChooseUser(item)"></i>
            </div>
        </div>
        <el-card class="box-card" shadow="false">
            <div slot="header" class="box-card-header">
                <el-image class="user-header" :src="fileDownloadUrl+currentChatUser.header"
                          v-if="users.length===1"></el-image>
                <div class="header-user-name">{{currentChatUser.name}}</div>
                <el-button icon="el-icon-close" style="float: right; padding: 3px 0;font-size: 20px;margin: 5px;"
                           type="text" title="关闭" @click="handleClose"></el-button>
                <el-button icon="el-icon-minus" style="float: right; padding: 3px 0;font-size: 20px;margin: 5px;"
                           type="text" title="最小化" @click="handleMini"></el-button>
            </div>
            <div class="user-right-content-show" ref="user-right-content-show">
                <div :class="{'chat-record-other': currLoginUser.id !== item.id,'chat-record-mine':currLoginUser.id === item.id}"
                     v-for="(item,index) in chatRecords" :key="index">
                    <div class="record-header">
                        <el-image class="user-header" style="border-radius: 45px;"
                                  :src="fileDownloadUrl+item.header"></el-image>
                    </div>
                    <div :class="{'record-info-left': currLoginUser.id !== item.id,'record-info-right':currLoginUser.id === item.id}">
                        <div :class="{'record-info-left-title': currLoginUser.id !== item.id,'record-info-right-title':currLoginUser.id === item.id}">
                            {{item.sendTime}}
                        </div>
                        <div :class="{'record-info-left-content': currLoginUser.id !== item.id,'record-info-right-content':currLoginUser.id === item.id}">
                            {{item.msgContent}}
                        </div>
                    </div>
                </div>
            </div>
            <el-divider></el-divider>
            <div class="funcArea">
                <div class="funcArea-msg-func">
                    <el-button type="text" style="color: #333333;font-size: 25px;height: 40px;"
                               icon="el-icon-camera"></el-button>
                </div>
                <div class="funcArea-msg-record">
                    <el-button type="text" style="color: #333333;" icon="el-icon-stopwatch">
                        聊天记录
                    </el-button>
                </div>
            </div>
            <div class="user-right-content-input">
                <el-input type="textarea" placeholder="请输入内容" v-model="inputContent"
                          @keydown.native="keyDownPrevent($event)"
                          rows="6" ref="inputRef"
                          resize="none"></el-input>
            </div>
            <el-dropdown size="small" split-button type="primary"
                         style="float: right;margin-right: 10px; height: 50px"
                         @click.stop="handleSubmit"
                         @command.passive="handleCommand">
                发 送
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item v-for="(item,index) in dropList" :key="index"
                                      :command="item.command"
                                      :disabled="item.disabled">
                        {{item.text}}
                    </el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
        </el-card>
    </div>
</template>

<script>
    export default {
        name: "ChatRoom",
        props: {
            //控制展示或隐藏聊天对话框
            chatDialogVisible: {
                type: Boolean,
                default: false,
                required: true
            },
            //选择的聊天对象
            chooseChatUser: {
                type: Object,
                required: true
            },
            //文件上传地址
            fileUploadUrl: {
                type: String,
                required: true
            },
            //文件下载地址
            fileDownloadUrl: {
                type: String,
                required: true
            }
        },
        computed: {
            //系统当前登录用户
            currLoginUser: function () {
                let userStr = sessionStorage.getItem("currLoginUser");
                return userStr ? JSON.parse(userStr) : null;
            },
            //左侧聊天列表
            users: function () {
                return this.$store.state.chatStore.dialogUsers;
            },
            //计算当前选中的聊天对象
            currentChatUser: {
                get: function () {
                    if (Object.keys(this.currChatUserTemp).length) {
                        return Object.keys(this.currChatUserTemp).length ? this.currChatUserTemp : null;
                    } else {
                        return Object.keys(this.chooseChatUser).length ? this.chooseChatUser : null;
                    }

                },
                set: function (val) {
                    this.currChatUserTemp = val;
                }
            }
        },
        watch: {
            //监听其他组件传递过来的聊天对象的信息
            chooseChatUser: function (newVal) {
                this.handleChooseUser(newVal);
            },
            //监听到当前聊天对象的信息
            currentChatUser: function (newVal) {
                console.log(`：${JSON.stringify(newVal)}`);
                this.loadChatRecord(newVal);
            }
        },
        data() {
            return {
                dropActive: false,
                dropList: [
                    {command: "enter_send", text: "按Enter键发送消息", disabled: true},
                    {command: "ctrl_enter_send", text: "按Ctrl+Enter键发送消息", disabled: false}
                ],
                dialogVisible: false,
                //发送方式
                sendWay: "enter_send",
                //当前选中的聊天对象零时对象（用于计算属性）
                currChatUserTemp: {},
                inputContent: null,
                chatRecords: []
            }
        },
        methods: {
            //处理选中的人员
            handleChooseUser(param) {
                //设置当前选中状态的css
                Object.keys(this.$refs).forEach(key => {
                    if (this.$refs[key] && this.$refs[key][0]) {
                        if (key === `chat-user-${param.id}`) {
                            this.$refs[key][0].className = "chat-user chat-user-active";
                        } else {
                            this.$refs[key][0].className = "chat-user";
                        }
                    }
                });
                //设置当前选中的人员
                this.currentChatUser = this._.assign({}, param);
                //查询与当前选中人员的聊天记录
                this.loadChatRecord(this.currentChatUser);
                this.scrollToBottom();
            },
            //移除选中的人员
            handleRemoveChooseUser(param) {
                this.$store.commit("removeDialogUser", param);
                this.handleChooseUser(this.users[0]);
            },
            //关闭窗口
            handleClose() {
                this.$emit("callBackFromSub", false);
                this.$store.commit("emptyDialogUser", []);
            },
            //最小化窗口
            handleMini() {
                this.$emit("callBackFromSub", false);
            },
            //处理键盘事件
            keyDownPrevent(event) {
                if (this.sendWay === "ctrl_enter_send" && event.ctrlKey && event.key === "Enter") {
                    // 发送文本
                    this.handleSubmit();
                    // 阻止浏览器默认换行操作
                    event.preventDefault();
                } else if (this.sendWay === "enter_send" && event.key === "Enter" && !event.ctrlKey) {
                    // 发送文本
                    this.handleSubmit();
                    // 阻止浏览器默认换行操作
                    event.preventDefault();
                }
                return false;
            },
            //点击发送按钮
            handleSubmit() {
                if (!this.inputContent || !this.inputContent.trim()) {
                    this.$errorMsg("发送内容不能空");
                } else {
                    let message = {
                        id: this.currLoginUser.id,
                        senderId: this.currLoginUser.id,
                        receiverId: this.currentChatUser.id,
                        header: this.currLoginUser.header,
                        name: this.currLoginUser.name,
                        sendTime: this.$formatDate(new Date(), "yyyy-MM-dd hh:mm:ss"),
                        msgContent: this.inputContent
                    };
                    console.log("发送的信息：", message)
                    this.$sendWSPush("single", message);
                    this.scrollToBottom();
                    this.inputContent = null;
                }
            },
            //选择发送方式
            handleCommand(e) {
                this.sendWay = e;
                this.dropList.forEach(o => {
                    o.disabled = o.command === e;
                })
            },
            //滚动到底部
            scrollToBottom() {
                this.$nextTick(() => {
                    if (this.$el.attributes) {
                        let content = this.$el.querySelector(".user-right-content-show");
                        content.scrollTop = content.scrollHeight;
                    }
                });
                if (this.$refs.inputRef) {
                    this.$refs.inputRef.focus()
                }
            },
            //加载聊天记录
            loadChatRecord(param) {
                if (param && param.id) {
                    this.$httpGet(this.$axiosIMInstance, "api/rest/imChatRecord/info/list", {
                        senderId: this.currLoginUser.id,
                        receiverId: param.id
                    }).then(res => {
                        if (res.code === 200) {
                            this.chatRecords = res.data;
                            this.$nextTick(() => {
                                this.scrollToBottom();
                            });
                        }
                    });
                }
            }
        },
        mounted() {
            this.scrollToBottom();
            let _this = this;
            //监听ws数据响应
            window.addEventListener('onmessageWS', function (e) {
                if (e.detail.messageEvent.data !== "pong" && e.detail.messageEvent.data !== "success") {
                    _this.loadChatRecord(_this.currentChatUser);
                }

            });
        }, destroyed() {
            window.removeEventListener('onmessageWS', function (e) {
            });
        }
    }
</script>

<style scoped lang="scss">
    .user-header {
        width: 50px;
        height: 50px;
        border-radius: 50px;
    }

    .chat-room-single {
        width: 850px !important;
        left: 26% !important;
    }

    .is-always-shadow {
        box-shadow: 0 0 10px 5px rgba(0, 0, 0, .1)
    }

    .chat-room {
        background-image: linear-gradient(160deg, rgb(57, 181, 255) 20%, rgb(91, 164, 255) 80%);
        z-index: 99999999;
        height: 700px;
        width: 600px;
        position: absolute;
        top: 15%;
        left: 25%;


        .box-card {
            display: inline-block;
            position: absolute;
            top: 0;
            right: 0;
            width: 650px;
            height: 700px;
            border-radius: 0;

            /deep/ .el-card__header {
                padding: 5px 10px;

                .box-card-header {
                    height: 50px;
                    line-height: 50px;

                    .header-user-name {
                        display: inline-block;
                        position: absolute;
                        width: 200px;
                        height: 50px;
                        line-height: 50px;
                        padding-left: 10px;
                        white-space: nowrap;
                        overflow: hidden;
                        text-overflow: ellipsis;
                    }
                }
            }

            /deep/ .el-card__body {
                padding: 0;

                /deep/ .el-divider--horizontal {
                    margin: 0;
                }
            }
        }

        .user-right-content-show {
            padding: 10px 10px;
            height: 415px;
            overflow-y: scroll;

            .chat-record-other {
                display: flex;
                flex-direction: row;

                .record-header {
                }

                .record-info-left {
                    .record-info-left-title {
                        width: 100%;
                        font-size: 14px;
                        padding-left: 15px;
                        height: 40px;
                        line-height: 40px;
                    }

                    .record-info-left-content {
                        word-break: break-all;
                        background: #0bc2ff;
                        color: #ffffff;
                        margin: 0 0 25px 10px;
                        max-width: 400px;
                        width: fit-content;
                        border-radius: 20px;
                        padding: 8px 15px;
                        line-height: 20px;
                    }
                }
            }

            .chat-record-mine {
                display: flex;
                flex-direction: row-reverse;

                .record-header {

                }

                .record-info-right {
                    display: flex;
                    flex-direction: column;
                    flex-wrap: wrap-reverse;

                    .record-info-right-title {
                        width: 100%;
                        font-size: 14px;
                        padding-right: 15px;
                        height: 40px;
                        line-height: 40px;
                        text-align: right;
                    }

                    .record-info-right-content {
                        word-break: break-all;
                        background: rgba(245, 248, 255, 0.07);
                        color: rgba(52, 52, 52, 0.93);
                        margin: 0 10px 25px 0;
                        max-width: 400px;
                        width: fit-content;
                        border-radius: 20px;
                        padding: 8px 15px;
                        line-height: 20px;
                        border: 0.5px solid lightgray;
                    }
                }
            }
        }

        .funcArea {
            width: 100%;
            height: 40px;
            display: flex;
            align-items: center;
            flex-direction: row;

            .funcArea-msg-func {
                flex: 1 1 0;
                line-height: 40px;
                height: 40px;
                padding-left: 15px;

                .el-button {
                    padding: 0;
                }
            }

            .funcArea-msg-record {
                flex: 0 0 100px;
                line-height: 40px;
                height: 40px;
            }
        }

        .user-right-content-input {
            height: 126px;

            /deep/ .el-textarea__inner {
                border-radius: 0;
                border: 1px solid transparent;
            }
        }

        .user-left-list {
            position: absolute;
            top: 0;
            display: inline-block;
            width: 200px;
            height: 700px;
            overflow-y: scroll;

            .chat-user {
                width: 199px;
                height: 60px;
                padding: 5px 10px;
                cursor: pointer;

                .user-name {
                    display: inline-block;
                    position: absolute;
                    width: 105px;
                    height: 50px;
                    line-height: 50px;
                    padding-left: 10px;
                    color: #ffffff;
                    white-space: nowrap;
                    overflow: hidden;
                    text-overflow: ellipsis;
                }

                .el-icon-circle-close {
                    visibility: hidden;
                    font-size: 18px;
                }


            }

            .chat-user-active {
                background-image: linear-gradient(160deg, rgb(58, 153, 255) 20%, rgb(68, 166, 255) 80%);
            }

            .chat-user:hover {
                background-image: linear-gradient(160deg, rgb(58, 153, 255) 20%, rgb(68, 166, 255) 80%);
                .el-icon-circle-close {
                    font-size: 18px;
                    float: right;
                    width: 30px;
                    height: 50px;
                    line-height: 50px;
                    text-align: center;
                    visibility: visible;
                }
            }
        }

    }

    @media screen and (max-width: 1500px) {
        .chat-room {
            position: absolute;
            top: 12%;
            left: 20%;
        }
    }

    @media screen and (max-width: 1300px) {
        .chat-room {
            position: absolute;
            top: 10%;
            left: 14%;
        }
    }

    /*修改滚动条样式--start*/
    /deep/ .el-textarea__inner::-webkit-scrollbar,
    .user-left-list::-webkit-scrollbar {
        width: 5px;
        height: 10px;
        display: none;
    }

    .user-right-content-show::-webkit-scrollbar {
        width: 5px;
        height: 10px;
    }

    /deep/ .el-textarea__inner::-webkit-scrollbar-track,
    .user-right-content-show::-webkit-scrollbar-track,
    .user-left-list::-webkit-scrollbar-track {
        background: rgb(239, 239, 239);
        border-radius: 2px;
    }

    /deep/ .el-textarea__inner::-webkit-scrollbar-thumb,
    .user-right-content-show::-webkit-scrollbar-thumb,
    .user-left-list::-webkit-scrollbar-thumb {
        background: #bfbfbf;
        border-radius: 10px;
    }

    /deep/ .el-textarea__inner::-webkit-scrollbar-thumb:hover,
    .user-right-content-show::-webkit-scrollbar-thumb:hover,
    .user-left-list::-webkit-scrollbar-thumb:hover {
        background: rgba(39, 161, 255, 0.92);
    }

    /deep/ .el-textarea__inner::-webkit-scrollbar-corner,
    .user-right-content-show::-webkit-scrollbar-corner,
    .user-left-list::-webkit-scrollbar-corner {
        background: rgba(39, 161, 255, 0.92);
    }

    /*修改滚动条样式--end*/
</style>